package com.alm.token.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.FundArealistResponse;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.FundArealistView;
import com.alm.token.utils.CityAdapter;
import com.alm.token.utils.LanguageUtils;
import com.alm.token.widget.QuickLocationBar;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by en on 2019/4/23.
 */

public class FundArealistActivity extends BaseActivity implements View.OnClickListener, FundArealistView<Object> {

    public static final int INTENT_RESULT_INTO_CODE = 100;//
    public static final int INTENT_RESULT_INTO_CODE1 = 1001;//
    public static final int INTENT_RESULT_SUCC_CODE = 101;//请求码正确
    public static final int INTENT_RESULT_ERR_CODE = 102;//请求码错误
    public static final String INTENT_RESULT_CODE_VAULE = "intent_result_code_value";//返回值城市代码
    public static final String INTENT_RESULT_NAME_VAULE = "intent_result_name_value";//返回值城市名称

    private ListView mCityLit;
    private ListView city_list_search;
    private EditText et_search;
    private LinearLayout ll_city_search_list;
    private LinearLayout ll_location;
    private TextView tv_location_name;

    private CityAdapter adapter;
    private CityAdapter adapterSearch;

    private ImageView iv_back;
    private TextView overlay;
    private QuickLocationBar mQuicLocationBar;
    private List<FundArealistResponse.DataBean> mCityNames = new ArrayList<>();
    private List<FundArealistResponse.DataBean> mCityNamesSearch = new ArrayList<>();
    FundArealistResponse fundArealistResponse1;


    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_fund_area_list;
    }

    @Override
    protected void initVariables() {
        String str = getJson("arealist", this);
        fundArealistResponse1 = new Gson().fromJson(str, FundArealistResponse.class);
    }

    @Override
    protected void initViews() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        mQuicLocationBar = (QuickLocationBar) findViewById(R.id.city_loactionbar);
        mQuicLocationBar.setOnTouchLitterChangedListener(new LetterListViewListener());
        mQuicLocationBar.setVisibility(LanguageUtils.getSetIndex() == 1 ? View.GONE : View.VISIBLE);
        overlay = (TextView) findViewById(R.id.city_dialog);
        mCityLit = (ListView) findViewById(R.id.city_list);
        city_list_search = (ListView) findViewById(R.id.city_list_search);
        et_search = (EditText) findViewById(R.id.et_search);
        ll_city_search_list = (LinearLayout) findViewById(R.id.ll_city_search_list);
        ll_location = (LinearLayout) findViewById(R.id.ll_location);
        tv_location_name = (TextView) findViewById(R.id.tv_location_name);

        mQuicLocationBar.setTextDialog(overlay);

        iv_back.setOnClickListener(this);
        tv_location_name.setOnClickListener(this);

//        initMapLocation();//定位相关
        tv_location_name.setText("定位中...");
    }

    @Override
    protected void loadData() {
        showWaitDialog();
        getCountry(fundArealistResponse1);
        hideWaitDialog();
        listenerSearchEdit();
    }

    @Override
    protected void onResume() {
        super.onResume();

        preenter.getCountryData();

//        if(mCityNames!=null&&mCityNames.size()!=0){
//            if(LanguageUtils.getSetIndex() == 1){
//                Collections.sort(mCityNames);
//                adapter.notifyDataSetChanged();
//            }
//        }
    }

    //搜索输入监听
    private void listenerSearchEdit() {
        mCityNamesSearch = new ArrayList<>();
        adapterSearch = new CityAdapter(FundArealistActivity.this, mCityNamesSearch);
        city_list_search.setAdapter(adapterSearch);

        et_search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 输入的内容变化的监听
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // 输入前的监听
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 输入后的监听
                if (TextUtils.isEmpty(et_search.getText().toString())) {
                    ll_city_search_list.setVisibility(View.GONE);
                    ll_location.setVisibility(View.GONE);
                    mCityLit.setVisibility(View.VISIBLE);
                    mQuicLocationBar.setVisibility(LanguageUtils.getSetIndex() == 1 ? View.GONE : View.VISIBLE);
                } else {
                    ll_city_search_list.setVisibility(View.VISIBLE);
                    ll_location.setVisibility(View.GONE);
                    mCityLit.setVisibility(View.GONE);
                    mQuicLocationBar.setVisibility(View.GONE);

                    mCityNamesSearch.clear();

                    for (int i = 0; i < mCityNames.size(); i++) {
                        if (LanguageUtils.getSetIndex() == 1 ? mCityNames.get(i).getCountrys().contains(et_search.getText().toString()) : mCityNames.get(i).getYingwen().contains(et_search.getText().toString())) {
                            mCityNamesSearch.add(mCityNames.get(i));
                        }
                    }

                    adapterSearch.notifyDataSetChanged();
                    //UiUtil.showToast(FundArealistActivity.this, et_search.getText().toString());
                }
            }
        });
    }


    @Override
    public void getData(Object o) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        }else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }
    }

    @Override
    public void onError(String error) {
//        showToast(error);
    }

    @Override
    public void ShowProgress() {

//        showWaitDialog();
    }

    @Override
    public void hideProgress() {

//        hideWaitDialog();
    }

    @Override
    public void getCountry(FundArealistResponse fundArealistResponse) {
        if (fundArealistResponse.getStatus() == 0 && fundArealistResponse.getData() != null) {
            mCityNames = fundArealistResponse.getData();
//            Collections.sort(mCityNames);
            adapter = new CityAdapter(FundArealistActivity.this, mCityNames);
            mCityLit.setAdapter(adapter);
            mCityLit.setOnItemClickListener(new CityListOnItemClick());
        } else {
//            showToast(fundArealistResponse.getMsg());
        }
    }


    //ListView监听-字母快速选择监听
    private class CityListOnItemClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
            FundArealistResponse.DataBean cityModel = (FundArealistResponse.DataBean) mCityLit.getAdapter().getItem(pos);
            //Toast.makeText(FundArealistActivity.this, cityModel.getAreaCode(), Toast.LENGTH_SHORT).show();
            String areaCode = cityModel.getNumbers();
            String cityName = cityModel.getCountrys();
            if (TextUtils.isEmpty(areaCode)) {
                setResult(INTENT_RESULT_ERR_CODE);
            } else {
                Intent intent = new Intent();
                intent.putExtra(INTENT_RESULT_CODE_VAULE, areaCode);
                intent.putExtra(INTENT_RESULT_NAME_VAULE, cityName);
                setResult(INTENT_RESULT_SUCC_CODE, intent);
            }
            finish();
        }
    }

    public void setItemClick(FundArealistResponse.DataBean cityModel) {
        String areaCode = cityModel.getNumbers();
        String cityName = LanguageUtils.getSetIndex() == 1 ? cityModel.getCountrys() : cityModel.getYingwen();
        if (TextUtils.isEmpty(areaCode)) {
            setResult(INTENT_RESULT_ERR_CODE);
        } else {
            Intent intent = new Intent();
            intent.putExtra(INTENT_RESULT_CODE_VAULE, areaCode);
            intent.putExtra(INTENT_RESULT_NAME_VAULE, cityName);
            setResult(INTENT_RESULT_SUCC_CODE, intent);
        }
        finish();
    }

    private class LetterListViewListener implements
            QuickLocationBar.OnTouchLetterChangedListener {

        @Override
        public void touchLetterChanged(String s) {
            // TODO Auto-generated method stub
            Map<String, Integer> alphaIndexer = adapter.getCityMap();
            //Toast.makeText(FundArealistActivity.this, s + "。。" + alphaIndexer.get(s) + "..." + alphaIndexer.size(), Toast.LENGTH_SHORT).show();
            if (alphaIndexer.get(s) != null) {
                int position = alphaIndexer.get(s);
                mCityLit.setSelection(position);
                //Toast.makeText(FundArealistActivity.this, position + "", Toast.LENGTH_SHORT).show();
            }
        }

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_location_name:
                FundArealistResponse.DataBean cityModel = null;
                String locationName = tv_location_name.getText().toString();
                for (int i = 0; i < mCityNames.size(); i++) {
                    if (mCityNames.get(i).getCountrys().contains(locationName)) {
                        cityModel = mCityNames.get(i);
                        break;
                    } else if (locationName.contains(mCityNames.get(i).getCountrys())) {
                        cityModel = mCityNames.get(i);
                        break;
                    }
                }

                //UiUtil.showToast(FundArealistActivity.this, cityModel.getCityName());
                setItemClick(cityModel);
                break;
        }

    }


    public String getJson(String fileName, Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}